#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoop.h"
#include "include/muduo/net/TcpConnection.h"

#include <iostream>
#include <functional>
#include <unordered_map>

class TranslateServer
{
public:
    TranslateServer(int port)
        : _server(&_baseloop, muduo::net::InetAddress(port), "Translate server", muduo::net::TcpServer::kNoReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::OnConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        _server.start(); // 开始事件监听 socket->reuse->bind->listen->poller
        _baseloop.loop(); // 开始事件监控
    }
    
    ~TranslateServer()
    {
    }


private: 
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
            std::cout << "get a new link" << std::endl;
        else
            std::cout << "link fail" << std::endl;
    }

    void OnMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        // 从buf取数据
        std::string str = buf->retrieveAllAsString();
        // 调用翻译接口
        std::string resp = tranlate(str);
        // 应答客户端
        conn->send(resp);
    }

    std::string tranlate(std::string str)
    {
        static std::unordered_map<std::string, std::string> dict_map = {
            {"hello", "你好"},
            {"Hello", "你好"},
            {"你好", "Hello"},
            {"吃了吗", "油泼面"}};
        auto it = dict_map.find(str);
        if (it == dict_map.end())
        {
            return "没听懂！！";
        }
        return it->second;
    }

private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};


int main()
{
    TranslateServer server(8888);
    server.start();

    return 0;
}